package com.hjc.service.impl;

import com.hjc.entity.OutStore;
import com.hjc.entity.Product;
import com.hjc.entity.Result;
import com.hjc.mapper.OutStoreMapper;
import com.hjc.mapper.ProductMapper;
import com.hjc.page.Page;
import com.hjc.service.OutStoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class OutStoreServiceImpl implements OutStoreService {
    @Autowired
    private OutStoreMapper outStoreMapper;
    @Autowired
    private ProductMapper productMapper;
    @Override
    public Result addOutStore(OutStore outStore) {
        int flag = outStoreMapper.insertOutStore(outStore);
        if (flag > 0) {
            return Result.ok("新增出库订单成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS, "新增出库订单失败！");
    }

    @Override
    public Page findOutStorePage(OutStore outStore, Page page) {
        int count = outStoreMapper.selectOutStoreCount(outStore);
        List<OutStore> outStoreList = outStoreMapper.selectOutStorePage(outStore, page);

        page.setTotalNum(count);
        page.setResultList(outStoreList);

        return page;
    }

    @Transactional
    @Override
    public Result confirmOutStore(OutStore outStore) {
//        拿到需要出库单商品
        Product product = productMapper.selectProductById(outStore.getProductId());

//        判断商品库存是否足够出货
        if (product.getProductInvent() < outStore.getOutNum()) {
            return Result.err(Result.CODE_ERR_BUSINESS, "出库数量大于库存，出库失败！");
        }

//        更新出货状态
        int flag1 = outStoreMapper.updateOutStoreIsOut(outStore.getOutsId());

//        更新商品库存
        if (flag1 > 0) {
            int flag2 = productMapper.updateProductInvent(outStore.getProductId(), -outStore.getOutNum());
            if (flag2 > 0) {
                return Result.ok("出库成功！");
            }
            return Result.err(Result.CODE_ERR_BUSINESS, "出库失败！");
        }

        return Result.err(Result.CODE_ERR_BUSINESS, "出库失败！");
    }
}
